package com.framework.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.framework.common.Enums.FrameworkErrorCodeEnum;
import com.framework.common.domain.R;
import com.framework.common.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.netty.ByteBufFlux;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author zhoubb
 * @version V1.0
 * @Date 2020/4/30 21:30
 * @since JDK 1.8
 */
@Component
@Slf4j
public class AccessFilter implements GlobalFilter,Ordered {

    // url匹配器
    private AntPathMatcher pathMatcher = new AntPathMatcher();

    @Autowired
    private RedisUtils redisUtils;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String accessToken = extractToken(exchange.getRequest());
        String path = exchange.getRequest().getPath().value();
        if(pathMatcher.match("/**/v2/api-docs/**",path)){
            return chain.filter(exchange);
        }

        if(!pathMatcher.match("/api-auth/**",path) && !pathMatcher.match("/**/api/**",path)
                && !pathMatcher.match("/**/wx/**",path)){
            if (accessToken == null) {
                log.info("访问url=[{}],获取到的accessToken为空",path);
                exchange.getResponse().setStatusCode(HttpStatus.OK);
                exchange.getResponse().getHeaders().add("Content-Type","application/json");
                return exchange.getResponse().writeAndFlushWith(Flux.just(ByteBufFlux.just(exchange.getResponse().bufferFactory().wrap(getWrapData()))));

            }else{
                try {
                    if(!redisUtils.hasKey("access:" + accessToken)){
                        log.info("访问url=[{}],accessToken[{}]已过期",path,accessToken);
                        exchange.getResponse().setStatusCode(HttpStatus.OK);
                        exchange.getResponse().getHeaders().add("Content-Type","application/json");
                        return exchange.getResponse().writeAndFlushWith(Flux.just(ByteBufFlux.just(exchange.getResponse().bufferFactory().wrap(getWrapData()))));
                        //return exchange.getResponse().setComplete();
                    }
                } catch (Exception e) {
                    exchange.getResponse().setStatusCode(HttpStatus.OK);
                    exchange.getResponse().getHeaders().add("Content-Type","application/json");
                    return exchange.getResponse().writeAndFlushWith(Flux.just(ByteBufFlux.just(exchange.getResponse().bufferFactory().wrap(getWrapData()))));

                }
            }
        }

        return chain.filter(exchange);
    }

    private byte[] getWrapData() {
        try {
            return new ObjectMapper().writeValueAsString(R.error(FrameworkErrorCodeEnum.TOKEN_FAIL)).getBytes();
        } catch (JsonProcessingException e) {
            //
        }
        return "".getBytes();
    }

    @Override
    public int getOrder() {
        return -10;
    }

    /**
     * 解析token
     * @param request
     * @return
     */
    protected String extractToken(ServerHttpRequest request) {
        List<String> strings = request.getHeaders().get("Authorization");
        String authToken = null;
        if (strings != null) {
            authToken = strings.get(0).substring("Bearer".length()).trim();
        }

        if (StringUtils.isBlank(authToken)) {
            strings = request.getQueryParams().get("access_token");
            if (strings != null) {
                authToken = strings.get(0);
            }
        }
        return authToken;
    }
}
